#include "mlist.h"

s_mlist *g_mlist = NULL;

int ran(int i)
{
  int nb;
  int nb2;

  nb = rand();
  nb2 = nb % i;
  return (nb2);
}

void delete_monster(s_mlist *dlist)
{
  s_mlist *tmp = g_mlist;

  if (dlist == NULL)
  {
  }
  else
  {
    if (g_mlist == dlist)
    {
      g_mlist = g_mlist->next;
      free(dlist);
    }
    else
    {
      while (tmp != NULL && tmp->next != dlist)
	tmp = tmp->next;
      if (tmp->next == dlist)
      {
	tmp->next = dlist->next;
	free(dlist);
      }
    }
  }
}

s_mlist *add_monster(s_monster *monster, int x, int y)
{
  s_monster     *m = init_monster(monster);
  s_mlist       *list = malloc(sizeof (s_mlist));

  if (g_mlist == NULL)
  {
    list->monster = m;
    list->next = NULL;
  }
  else
  {
    list->monster = m;
    list->next = g_mlist;
  }
  list->monster->coord.x = x;
  list->monster->coord.y = y;
  g_mlist = list;

  return (list);
}

void check_monster()
{
  s_mlist *tmp = g_mlist;

  while (tmp != NULL)
  {
    if (tmp->monster->alive == 0)
      delete_monster(tmp);
    tmp = tmp->next;
  }
}

int draw_monster(SDL_Surface *area)
{
  s_mlist *tmp = g_mlist;
  s_monster *mons;

  check_monster();
  while (tmp != NULL)
  {
    mons = tmp->monster;
    draw_rect(mons->coord.x,
	      mons->coord.y,
	      mons->img,
	      area);
    tmp = tmp->next;
  }
  return (0);
}

int update_monster(SDL_Surface *area)
{
  s_mlist *tmp;

  tmp = g_mlist;
  while (tmp != NULL)
  {
    tmp->monster->coord.y += 1;
    if (tmp->monster->coord.y > area->h)
      delete_monster(tmp);
    tmp = tmp->next;
  }
  return (0);
}

int put_monster(SDL_Surface *area)
{
  int nb;
  int nb2;
  int nb3;

  if (g_mlist == NULL)
  {
    nb = ran(12);
    if (nb != 5)
      for (int i = 0; i <= nb; i++)
      {
	nb2 = ran(area->w);
	nb3 = ran(100);
	add_monster(g_monster[0], nb2, nb3);
      }
    else
      for (int i = 0; i <= nb; i++)
      {
        nb2 = ran(area->w);
        nb3 = ran(100);
        add_monster(g_monster[1], nb2, nb3);
      }
  }
  update_monster(area);
  draw_monster(area);
  return (0);
}

int free_monster()
{
  s_mlist *tmp;

  while (g_mlist != NULL)
  {
    tmp = g_mlist;
    g_mlist = g_mlist->next;
    delete_monster(tmp);
  }
  free(g_monster);

  return (0);
}
